<template>
  <Dialog :funcConfirm="handleConfirm"
          :funcCancel="handleClose"
          :headerTitle="headerTitle"
          :confirmTitle="confirmTitle"
          :open="open">
    <template v-slot:body>
      <div class="content-wrapper">
        <div v-for="(item, i) of items" :key="i">
          <div class="content-row" :class="{fixed: item.key == 'image'}">
            <div class="row-name">
              <span class="name-required" v-if="i<3">{{'*'}}</span>
              <span class="name-text">{{item.title}}</span>
            </div>
            <div class="input-box" v-if="item.key != 'datetime'">
              <input v-if="item.key != 'image'"
                     type="text"
                     v-model="item.value"
                     maxlength="20"
                     minlength="2"
                     placeholder="">
              <span v-else>{{dataImage.name}}</span>
            </div>
            <div class="input-box" v-else>
              <el-date-picker
                  v-model="selectedDate"
                  type="datetime"
                  placeholder="">
              ></el-date-picker>
            </div>
          </div>
          <div class="image-box" v-if="item.key == 'image'">
            <div class="image-grid" v-for="(image) of images" :key="image.id"
                 :class="{active: dataImage.value == image.url}"
                 @click="dataImage.value = image.url, dataImage.name = image.name">
              <img class="image-item" :src=image.url>
              <img class="image-selected" v-if="dataImage.value == image.url" src="@media/expo/icon-select@2x.png">
            </div>
          </div>
        </div>
      </div>
    </template>
  </Dialog>
</template>

<script>

import exhibitionService from "@api/exhibitionService";
import Dialog from "@/component/dialog/Dialog";
import {$formatDate} from "@/utils/tools"
import {Message} from "element-ui";

export default {
  components: {Dialog},
  props: {
    funcConfirm: Function
  },
  data() {
    return {
      headerTitle: '',
      confirmTitle: '',
      items: [
        {
          title: '名 称：',
          key: 'name',
          value: ''
        },
        {
          title: '图 标：',
          key: 'image',
          name: '',
          value: ''
        },
        {
          title: '时 间：',
          key: 'datetime',
          value: ''
        },
        {
          title: '地 点：',
          key: 'address',
          value: ''
        },
        {
          title: '规 模：',
          key: 'scale',
          value: ''
        },
      ],
      selectedDate: '',
      images: []
    }
  },
  // 监听属性 类似于data概念
  computed: {
    open() {
      const isOpen = this.$store.state.dialog.isOpenCreateExpo || this.$store.state.dialog.isOpenEditExpo
      return isOpen
    },
    isCreate() {
      return this.$store.state.dialog.isOpenCreateExpo
    },
    dataName() {
      return this.findData('name')
    },
    dataImage() {
      return this.findData('image')
    },
    dataDate() {
      return this.findData('datetime')
    },
    dataAddress() {
      return this.findData('address')
    },
    dataScale() {
      return this.findData('scale')
    },
  },
  // 监控data中的数据变化
  watch: {
    selectedDate(value) {
      if (!value) {
        return
      }
      this.dataDate.value = $formatDate(value, "yyyy-MM-dd hh:mm:ss")
    },
    open(value) {
      if (!value) {
        return
      }
      if (this.isCreate) {
        this.headerTitle = '新建展区'
        this.confirmTitle = '创建'
        this.dataName.value = ''
        this.dataImage.value = ''
        this.dataImage.name = ''
        this.dataDate.value = ''
        this.dataAddress.value = ''
        this.dataScale.value = ''
      } else {
        this.headerTitle = '编辑模块'
        this.confirmTitle = '完成'
        const item = this.$store.state.dialog.editExpoItem
        this.dataName.value = item.name
        this.dataImage.value = item.image
        this.dataDate.value = item.datetime
        this.dataAddress.value = item.address
        this.dataScale.value = item.scale
        this.dataImage.name = this.images.filter((image)=>{
          return image.url == item.image
        })[0].name
        this.selectedDate = new Date(item.datetime)
        console.log(item.datetime)
        console.log(new Date(item.datetime))
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.fetchImages()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    handleClose() {
      const commitType = this.isCreate ? 'dialog/CREATE_EXPO_OPEN' : 'dialog/EDIT_EXPO_OPEN'
      this.$store.commit(commitType, false)
    },
    handleConfirm() {
      if (this.dataName.value == '') {
        Message.warning('请输入名称')
        return
      }
      if (this.dataDate.value == '') {
        Message.warning('请输入时间')
        return
      }
      if (this.isCreate) {
        this.createExpo()
        return
      }
      this.editExpo()
    },
    fetchImages() {
      exhibitionService.getCreateImage().then(res => {
        this.images = res.data.data
        const defaultImage = this.images[0]
        if (defaultImage) {
          this.dataImage.name = defaultImage.name
          this.dataImage.value = defaultImage.url
        }
      }).catch((res) => {
        console.log(res)
      })
    },
    createExpo() {
      let params = {}
      this.items.map((item)=>{
        params[item.key] = item.value
      })
      exhibitionService.createExpo(params).then(res => {
        console.log(res.data.data)
        this.funcConfirm()
        this.handleClose()
      }).catch((res) => {
        console.log(res)
      })
    },
    editExpo() {
      const originItem = this.$store.state.dialog.editExpoItem

      console.log(originItem)
      console.log(this.items)

      let isEdit = false
      let params = {}
      if (this.dataName.value != originItem.name) {
        isEdit = true
        params['name'] = this.dataName.value
      }
      if (this.dataImage.value != originItem.image) {
        isEdit = true
        params['image'] = this.dataImage.value
      }
      if (this.dataDate.value != originItem.datetime) {
        isEdit = true
        params['datetime'] = this.dataDate.value
      }
      if (this.dataAddress.value != originItem.address) {
        isEdit = true
        params['address'] = this.dataAddress.value
      }
      if (this.dataScale.value != originItem.scale) {
        isEdit = true
        params['scale'] = this.dataScale.value
      }
      if (!isEdit) {
        this.handleClose()
        return
      }

      exhibitionService.editExpo(originItem.uid, params).then(res => {
        console.log(res.data.data)
        this.funcConfirm()
        this.handleClose()
      }).catch((res) => {
        console.log(res)
      })
    },
    findData(type) {
      return this.items.filter((item)=>{
        return item.key == type
      })[0] || {}
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped lang="scss">
@import "@/style/scss/component/dialog/createExpoDialog.scss"
</style>
<style lang="scss">
.el-date-editor.el-input {
  .el-input__inner {
    background: transparent;
    border: transparent;
    color: #2F8AEE;
    font-size: 16px;
  }
  .el-icon-time {
    &:before {
      content: '';
    }
  }
}
</style>
